<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="medium"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item prop="searchValue">
        <el-input
          v-model="queryParams.searchValue"
          placeholder="请输入课程名称/描述/标签"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="medium" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="medium" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['course:course:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['course:course:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="6">
        <div class="inner-select">
          <span>是否开课：</span>
          <el-select
            v-model="queryParams.courseIsBegin"
            placeholder="请选择"
            size="small"
            @change="changeCourseIsBegin"
            :clearable="true"
          >
            <el-option
              v-for="dict in dict.type.course_is_begin"
              :value="dict.value"
              :label="dict.label"
            ></el-option>
          </el-select>
        </div>
      </el-col>
      <el-col :span="6">
        <div class="inner-select">
          <span>是否公开：</span>
          <el-select
            v-model="queryParams.courseIsPublic"
            placeholder="请选择"
            size="small"
            @change="changeCourseIsPublic"
            :clearable="true"
          >
            <el-option
              v-for="dict in dict.type.course_is_public"
              :value="dict.value"
              :label="dict.label"
            ></el-option>
          </el-select>
        </div>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="courseList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column
        label="课程标题"
        width="100"
        align="center"
        prop="courseTitle"
        :show-overflow-tooltip="true"
      />
      <el-table-column label="课程描述" align="center" prop="courseDesc" :show-overflow-tooltip="true" />
      <el-table-column label="课程封面" align="center" prop="courseCover" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <el-image
            class="courseImg"
            :src="scope.row.courseCover"
            :preview-src-list="[scope.row.courseCover]"
          ></el-image>
        </template>
      </el-table-column>
      <el-table-column
        label="课程标签"
        align="center"
        prop="courseFlag"
        width="180px"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <my-tag :valStr="scope.row.courseFlag" />
        </template>
      </el-table-column>
      <el-table-column
        label="开课时间"
        align="center"
        prop="courseBeginDate"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.courseBeginDate, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="结课时间"
        align="center"
        prop="courseEndDate"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.courseEndDate, '{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="是否开课" align="center" prop="courseIsBegin">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="手动调节是否开课" placement="top">
            <dict-tag :options="dict.type.course_is_begin" :value="scope.row.courseIsBegin" />
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="是否公开" align="center" prop="courseIsPublic">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark" content="公开的课程不经过学习计划" placement="top">
            <dict-tag :options="dict.type.course_is_public" :value="scope.row.courseIsPublic" />
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['course:course:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['course:course:remove']"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-s-data"
            @click="handleChapterList(scope.row.courseId)"
            v-hasPermi="['course:chapter:list']"
          >章节列表</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleCourseInfo(scope.row)"
          >详情</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改课程对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="课程标题" prop="courseTitle">
          <el-input v-model="form.courseTitle" placeholder="请输入课程标题" />
        </el-form-item>
        <el-form-item label="课程描述" prop="courseDesc">
          <el-input v-model="form.courseDesc" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="课程封面" prop="courseCover">
          <image-upload v-model="form.courseCover" :fileSize="2" />
        </el-form-item>
        <el-form-item label="课程标签(不超过两个)" prop="courseFlag">
          <el-select
            v-model="tags"
            multiple
            filterable
            allow-create
            default-first-option
            placeholder="请输入课程标签(不超过两个)"
            @change="change"
          ></el-select>
        </el-form-item>
        <el-form-item label="开课时间" prop="courseBeginDate">
          <el-date-picker
            clearable
            v-model="form.courseBeginDate"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择开课时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="结课时间" prop="courseEndDate">
          <el-date-picker
            clearable
            v-model="form.courseEndDate"
            type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择结课时间"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="是否开课" prop="courseIsBegin">
          <el-select v-model="form.courseIsBegin" placeholder="请选择" :clearable="true">
            <el-option
              v-for="dict in dict.type.course_is_begin"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="是否公开" prop="courseIsPublic">
          <el-select v-model="form.courseIsPublic" placeholder="请选择" :clearable="true">
            <el-option
              v-for="dict in dict.type.course_is_public"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 课程详情 -->
    <course-info :visible.sync="courseInfo.show" :courseData="courseInfo.data" />
  </div>
</template>

<script>
import {
  listCourse,
  getCourse,
  delCourse,
  addCourse,
  updateCourse
} from "@/api/course/course";
import CourseInfo from "@/components/Course/courseInfo.vue";
export default {
  name: "Course",
  dicts: ["course_is_begin", "course_is_public"],
  components: {
    CourseInfo
  },
  data() {
    return {
      // courseInfo
      courseInfo: {
        data: {},
        show: false
      },
      // 课程标签
      tags: [],
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 课程表格数据
      courseList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        searchValue: undefined,
        courseIsBegin: undefined,
        courseIsPublic: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        courseTitle: [
          { required: true, message: "课程标题不能为空", trigger: "blur" }
        ],
        courseBeginDate: [
          { required: true, message: "开课时间不能为空", trigger: "blur" }
        ],
        courseEndDate: [
          { required: true, message: "结课时间不能为空", trigger: "blur" }
        ],
        courseIsBegin: [
          { required: true, message: "是否开课不能为空", trigger: "blur" }
        ],
        courseIsPublic: [
          { required: true, message: "是否公开不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    changeCourseIsBegin() {
      console.log(this.queryParams.courseIsBegin);
      this.getList();
    },
    changeCourseIsPublic() {
      console.log(this.queryParams.courseIsPublic);
      this.getList();
    },
    change() {
      let tagStr = "";
      this.tags.forEach(e => {
        tagStr += e + ",";
      });
      this.form.courseFlag = tagStr;
      console.log(this.form.courseFlag);
    },
    /** 查询课程列表 */
    getList() {
      this.loading = true;
      listCourse(this.queryParams).then(response => {
        this.courseList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        courseId: undefined,
        courseTitle: "",
        courseDesc: "",
        courseCover: "",
        courseFlag: "",
        courseBeginDate: null,
        courseEndDate: null,
        courseIsBegin: 1,
        courseIsPublic: 1
      };
      this.resetForm("form");
      this.tags = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.queryParams.courseIsBegin = undefined;
      this.queryParams.courseIsPublic = undefined;

      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.courseId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加课程";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const courseId = row.courseId || this.ids;
      getCourse(courseId).then(response => {
        this.loading = false;
        this.form = response.data;
        let tags = response.data.courseFlag;
        if (tags != null || tags != undefined) {
          this.tags = tags.split(",");
        }
        this.open = true;
        this.title = "修改课程";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // this.buttonLoading = true;
          // 去除标签末尾的最后一个逗号
          if (this.form.courseFlag != null) {
            this.form.courseFlag = this.form.courseFlag.replace(/,$/gi, "");
          }
          if (this.form.courseId != null) {
            updateCourse(this.form)
              .then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addCourse(this.form)
              .then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const courseIds = row.courseId || this.ids;
      this.$modal
        .confirm('是否确认删除课程编号为"' + courseIds + '"的数据项？')
        .then(() => {
          this.loading = true;
          return delCourse(courseIds);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 跳转到该课程的章节 */
    handleChapterList(id) {
      this.$router.push("/course/course/chapter/" + id);
    },
    /** 课程详情 */
    handleCourseInfo(row) {
      this.courseInfo.data = row;
      this.courseInfo.show = true;
    }
  }
};
</script>
<style scoped>
.courseImg {
  display: block;
  margin: auto;
  width: 120px;
  height: 60px;
}
.inner-select {
  display: flex;
  justify-content: center;
}
.inner-select span {
  font-size: 16px;
  color: #909399;
  line-height: 32px;
}
</style>